<?php
class CPyramidMemberAccount extends Zend_Db_Table
{
	protected $_name = '';
	protected $_primary = '';
	
	public function __construct()
	{
		$this->_name = R_PRE . 'pyramid_member_account';
		$this->_primary = 'account_id';
		parent::__construct();
	}
	
	public function getMyCash($facebookId)
	{
		$db = $this->getAdapter();
		$where = $db->quoteInto('facebook_id = ?', $facebookId);
		
		$sql = 'select * from ' . $this->_name . ' where ' . $where;
		$result = $db->fetchAll($sql);
		if ($result) {
			return $result[0]['amount'];
		}
		return 0;
	}
	
	public function getRank($facebookId)
	{
		$db = $this->getAdapter();
		$where = $db->quoteInto('facebook_id = ?', $facebookId);
		
		$sql = 'select count(*) as c from ' . $this->_name . ' where amount > (select amount from ' . $this->_name . ' where ' . $where . ')';
		$result = $db->fetchAll($sql);
		
		return $result[0]['c'] + 1;		
	}
	
	public function subAmount($amount, $facebookId)
	{
		$db = $this->getAdapter();
		$where = $db->quoteInto('facebook_id = ?', $facebookId);
		
		$sql = 'update ' . $this->_name . ' set amount=amount - ' . $amount . ' where ' . $where;
		
		return $db->query($sql);
	}
	
	public function addAmount($amount, $facebookId)
	{
		$db = $this->getAdapter();
		$where = $db->quoteInto('facebook_id = ?', $facebookId);
		
		$sql = 'select * from ' . $this->_name . ' where ' . $where;
		$result = $db->fetchAll($sql);		
		if (empty($result)) {
			$sql = 'insert into ' . $this->_name . ' (amount, facebook_id, last_change_time) values(' .$amount. ', ' .$facebookId. ', ' .time(). ')';
		} else {
			$sql = 'update ' . $this->_name . ' set amount=amount + ' . $amount . ' where ' . $where;
		}
	
		return $db->query($sql);
	}
}